package com.zimmur.app.mocolink.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.RedisSystemException;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.zimmur.app.mocolink.dao.BackgroundImageMapper;
import com.zimmur.app.mocolink.domain.model.BackgroundImage;
import com.zimmur.app.mocolink.domain.model.BackgroundImageExample;
import com.zimmur.app.mocolink.service.IBackgroundImageService;
import com.zimmur.app.mocolink.service.RedisCacheUtil;

@Service
public class BackgroundImageServiceImpl implements IBackgroundImageService {
	private static final Logger log = LoggerFactory.getLogger(BackgroundImageServiceImpl.class);
	@Autowired
	private BackgroundImageMapper backgroundImageMapper;
	@Autowired
	private RedisCacheUtil<String> redisUtil;
	
	private static final String redis_key="mocolink_backImg_";
	
	@Override
	public List<BackgroundImage> selectByType(int type) {
		String key=redis_key+type;
		List<BackgroundImage> list;
		
		try {
			boolean isExist=redisUtil.exists(key);
			if(isExist){
				String json = redisUtil.getCacheString(key);
				list=JSONObject.parseArray(json, BackgroundImage.class);
			}else{
				synchronized (redis_key) {
					isExist=redisUtil.exists(key);
					if(isExist){
						String json = redisUtil.getCacheString(key);
						list=JSONObject.parseArray(json, BackgroundImage.class);
					}else{
						list = backgroundImageMapper.selectByType(type);
						if(list!=null){
							String json = JSONObject.toJSONString(list);
							try {
								redisUtil.setCacheString(key, json);
								redisUtil.setTimeout(key, redisUtil.longTime);
							} catch (RedisSystemException e) {
								log.error("redis save error,info:{}",e);
							}
						}
					}
				}
			}
		} catch (RedisSystemException e) {
			log.error("redis read error,info:{}",e);
			list=new ArrayList<>();
		}
		return list;
	}

	@Override
	public int update(BackgroundImage image) {
		int flag = backgroundImageMapper.updateByPrimaryKeySelective(image);
		if(flag>0){
			try {
				int type=image.getType();
				String key=redis_key+type;
				redisUtil.del(key);
			} catch (RedisSystemException e) {
				log.error("redis delete error,info:{}",e);
			}
		}
		return flag;
	}

	@Override
	public List<BackgroundImage> selectAll() {
		BackgroundImageExample example = new BackgroundImageExample();
		example.setOrderByClause("type asc ,site asc");
		return backgroundImageMapper.selectByExample(example);
	}

	@Override
	public BackgroundImage selectById(Integer id) {
		return backgroundImageMapper.selectByPrimaryKey(id);
	}

}
